<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of soaUsers
 *
 * @author dxx
 */

namespace app\common\model\oms;

use app\common\model\jsm\Cards as CardsModel;
use app\common\model\jsm\Mps as MpsModel;
use app\common\model\oms\StoreAuth as StoreAuthModel;
use think\Model;

class Store extends Model {

    protected $table = 'stores';
    protected $connection = ['database' => 'oms'];

    /**
     * 通过条件获取职员门店关系表
     * @param type $condition
     * @param type $field
     * @return type
     */
    public function getStoreByCondition($condition, $field = '*') {
        return $this->where($condition)->field($field)->find();
    }

    /**
     * 获取每个字段的值
     * @param type $condition
     * @param type $value
     * @return type
     */
    public function getStoreInfoStrByCondition($condition, $field = '') {
        return $this->where($condition)->value($field);
    }

    /**
     * 获取门店详情
     * @param type $storeId
     * @return type
     */
    public function detail($storeId, $companyId = '') {

        if (empty($storeId)) {
            return [];
        }

        $storeInfo = $this->where(['store_id' => $storeId])->find();
        if (!empty($storeInfo)) {
            $companiesModel = new Companies();
            $companies = $companiesModel->getCompanyInfoByCondition('*', ['company_id' => $storeInfo['company_id']]);
            $storeInfo['company_name'] = isset($companies['name']) ? $companies['name'] : '';

            $storeInfo['opening_hours'] = $storeInfo['store_open_time'] . '-' . $storeInfo['store_close_time'];
            if (!empty($companyId)) {
                $storeAuthModel = new StoreAuth();
                $storeAuth = $storeAuthModel->getStoreAuthByCondition([
                    'o_id2'    => $companyId,
                    'store_id' => $storeId
                ]);
                $storeInfo['partner_id'] = $storeAuth['partner_id'];
                $storeInfo['auth_id'] = $storeAuth['auth_id'];
            }
        }

        return $storeInfo;
    }

    //查找门店信息
    public function get_store_info($store_id) {
        return $this->field('store_id,store_show_name,store_province,store_name,store_address,store_latitude,store_longitude,store_city,store_district,store_telephone,store_open_time,store_close_time,store_photo_cover')
                        ->where(['store_id' => $store_id])
                        ->find();
    }

    /**
     * 通过坐标和优惠券id获取适用门店列表
     * @param type $coordinate
     * @param type $storeIdList(优惠券使用门店id列表)
     * @param type $page
     * @param type $pageSize
     * @param type $orderBy
     * @param type $cityId
     * @param type $regionId
     * @return boolean
     */
    public function getCouponsStore($coordinate, $storeIdList, $page, $pageSize, $orderBy = 'distance ASC', $cityId = '', $regionId = '') {
        //传入了城市，当然只计算本城市的门店啦
        $filed = "store_id,store_photo_cover, store_photo_list,company_id,store_show_name,store_address,wx_poi_id, region_city_id, region_district_id";

        list($Longitude, $Latitude) = explode(',', $coordinate);        //分解经纬度

        if ($Latitude < 3 || $Longitude < 3) {
            return false;
        }

        if ($cityId != '' || $regionId != '') {
            $sql = "SELECT * FROM  (  SELECT " . $filed . ",store_longitude,store_latitude, getDistance('$Longitude','$Latitude',store_longitude,store_latitude) distance  FROM stores "
                    . "WHERE store_id in(" . implode(',', $storeIdList) . ") AND store_longitude<>'' ";
            if ($cityId != '') {
                $sql .= " AND region_city_id=" . $cityId;
            }
            if ($regionId != '') {
                $sql .= " AND region_district_id=" . $regionId;
            }
            $sql .= " AND is_delete=0 AND store_status=1 AND is_virtual_store=0";
            $sql .= " ORDER BY " . $orderBy . " ) a ";
        } else {

            //这里为了加快计算效率，只做了根据经纬度去计算一定范围内的门店，拉去所有门店，会影响计算效率
            $Longitude1 = $Longitude - 1;
            $Longitude2 = $Longitude + 1;
            $Latitude1 = $Latitude - 1;
            $Latitude2 = $Latitude + 1;

            $sql = "SELECT * FROM  (  SELECT " . $filed . ",store_longitude,store_latitude, getDistance('$Longitude','$Latitude',store_longitude,store_latitude) distance FROM stores "
                    . "WHERE store_id in(" . implode(',', $storeIdList) . ") AND store_status=1 AND store_longitude<>'' AND store_longitude > '{$Longitude1}' AND store_longitude < '$Longitude2' and store_latitude > '{$Latitude1}' AND  store_latitude < '$Latitude2' "
                    . " AND is_delete=0 AND store_status=1  AND is_virtual_store=0 ORDER BY " . $orderBy . " ) a ";   //做了根据距离排序了
        }

        $count = $this->query(str_replace('*', 'count(*) as count', $sql));
        $start = ($page - 1) * $pageSize;
        $sql .= " limit $start,{$pageSize}";

        $storeList = [];
        if (!empty($count)) {
            $storeList = $this->query($sql);
            foreach ($storeList as $key => $list) {
                $companiesModel = new Companies();
                $storeList[$key]['company_name'] = $companiesModel->where(['company_id' => $list['company_id']])->value('name');

                $mpsModel = new MpsModel();
                $mps = $mpsModel->where(['o_id' => $list['company_id']])->find();
                if (empty($mps)) {
                    $storeList[$key]['card_name'] = '';
                }

                //获取mpId
                $CardsModel = new CardsModel();
                $card = $CardsModel->getOne(['mp_id' => $mps['mp_id'], 'location_id_list' => ['like', "%{$list['wx_poi_id']}%"]]);

                $storeList[$key]['card_name'] = !empty($card['title']) ? $card['title'] : '';
            }
        }

        return [
            'page'  => $page,
            'count' => $count[0]['count'],
            'list'  => $storeList
        ];
    }

    /**
     * 获取门店可用设备接口
     */
    public function getStoreOptometryDeviceByStoreId($storeId) {
        $res = $this
                ->alias('store')
                ->field('cod.id cod_id, sod.id sod_id')
                ->join('store_optometry_device sod', 'sod.store_id = store.store_id', 'INNER')
                ->join('company_optometry_device cod', 'cod.id = sod.cod_id', 'INNER')
                ->where(['store.store_id' => $storeId, 'sod.delete_time' => ['exp', 'is null']])
                ->select();
        return $res;
    }

    /**
     * 通过坐标获取门店列表
     * @param type $coordinate
     * @param type $mpid
     * @param type $pageCondition
     * @param type $orderBy
     * @param type $cityId
     * @param type $regionId
     * @return boolean
     */
    public function Lists($coordinate, $mpid, $page, $pageSize, $orderBy = 'distance ASC', $cityId = '', $regionId = '') {
        if (empty($mpid)) {
            return false;
        }
        if (empty($coordinate)) {
            return false;
        }
        $mpsModel = new MpsModel();
        $company_id = $mpsModel->where(['mp_id' => $mpid])->value('o_id'); //获取集团ID 

        $StoreAuthModel = new StoreAuthModel;
        $storeIdList = $StoreAuthModel->where(['o_id2' => $company_id,'auth_status'=>1])->column('store_id'); //获取集团被授权门店列表ID 
        if (empty($storeIdList)) {
            return false;
        }
        //传入了城市，当然只计算本城市的门店啦
        $filed = "store_id,store_photo_cover, store_photo_list,company_id,store_show_name,store_address,wx_poi_id, region_city_id, region_district_id";

        list($Longitude, $Latitude) = explode(',', $coordinate);        //分解经纬度

        if ($Latitude < 3 || $Longitude < 3) {
            return false;
        }

        if ($cityId != '' || $regionId != '') {
            $sql = "SELECT * FROM  (  SELECT " . $filed . ",store_longitude,store_latitude, getDistance('$Longitude','$Latitude',store_longitude,store_latitude) distance  FROM stores "
                    . "WHERE store_id in(" . implode(',', $storeIdList) . ") AND store_longitude<>'' ";
            if ($cityId != '') {
                $sql .= " AND region_city_id=" . $cityId;
            }
            if ($regionId != '') {
                $sql .= " AND region_district_id=" . $regionId;
            }
            $sql .= " AND is_delete=0 AND store_status=1 AND is_virtual_store=0";
            $sql .= " ORDER BY " . $orderBy . " ) a ";
        } else {

            //这里为了加快计算效率，只做了根据经纬度去计算一定范围内的门店，拉去所有门店，会影响计算效率
            $Longitude1 = $Longitude - 1;
            $Longitude2 = $Longitude + 1;
            $Latitude1 = $Latitude - 1;
            $Latitude2 = $Latitude + 1;

            $sql = "SELECT * FROM  (  SELECT " . $filed . ",store_longitude,store_latitude, getDistance('$Longitude','$Latitude',store_longitude,store_latitude) distance FROM stores "
                    . "WHERE store_id in(" . implode(',', $storeIdList) . ") AND store_longitude<>'' AND store_longitude > '{$Longitude1}' AND store_longitude < '$Longitude2' and store_latitude > '{$Latitude1}' AND  store_latitude < '$Latitude2' "
                    . " AND is_delete=0 AND store_status=1  AND is_virtual_store=0 ORDER BY " . $orderBy . " ) a ";   //做了根据距离排序了
        }

        $count = $this->query(str_replace('*', 'count(*) as count', $sql));
        $start = ($page - 1) * $pageSize;
        $sql .= " limit $start,{$pageSize}";

        $storeList = [];
        if (!empty($count)) {
            $storeList = $this->query($sql);
            foreach ($storeList as $key => $list) {
                $companiesModel = new Companies();
                $storeList[$key]['company_name'] = $companiesModel->where(['company_id' => $list['company_id']])->value('name');

                $mpsModel = new MpsModel();
                $mps = $mpsModel->where(['o_id' => $list['company_id']])->find();
                if (empty($mps)) {
                    $storeList[$key]['card_name'] = '';
                }

                //获取mpId
                $CardsModel = new CardsModel();
                $card = $CardsModel->getOne(['mp_id' => $mps['mp_id'], 'location_id_list' => ['like', "%{$list['wx_poi_id']}%"]]);

                $storeList[$key]['card_name'] = !empty($card['title']) ? $card['title'] : '';
            }
        }

        return [
            'page'  => $page,
            'count' => $count[0]['count'],
            'list'  => $storeList
        ];
    }

}
